// 引入formidable模块
const formidable = require('formidable')
const path = require('path')

// 引入文章集合对象
const { Article } = require('../../models/article')

module.exports = (req, res, next) => {
    // 1、创建表单解析对象, keepExtensions = true,保留文件后缀名
    const form = new formidable.IncomingForm({keepExtensions: true});
    // 2、配置上传文件的存放位置
    form.uploadDir = path.join(__dirname, '../../public/uploads');
    
    // 4、解析表单
    form.parse(req, async (err, fields, files) => {
        // err 错误对象
        // fields 请求中普通参数
        // files 上传文件
        try {
            await Article.create({
                title: fields.title[0],
                author: fields.author[0],
                publishDate: fields.publishDate[0],
                cover: files.cover[0].filepath.split('public')[1],
                content: fields.content[0],
            });
        } catch (error) {
            console.log('ghusdhisdhjsdhjfdshhdfjk:', error);
            return next(JSON.stringify({path: '/admin/article-edit', message: error.message || ''}))
        }

        res.redirect('/admin/article');
    })
}